package com.example.huadu_server.user.controller;

import com.example.huadu_server.user.dto.UserRegisterDTO;
import com.example.huadu_server.user.dto.UserLoginDTO; // 登录DTO
import com.example.huadu_server.user.service.UserAuthService;
import com.example.huadu_server.config.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/user/auth")
public class UserAuthController {

    @Autowired
    private UserAuthService userAuthService;

    /*
          注册
     */
    // 发送注册验证码
    @GetMapping("/registerCode")
    public ResponseEntity<Response<String>> sendRegisterCode(@RequestParam String email) {
        // 获取发送验证码的响应
        Response<String> response = userAuthService.sendRegisterCode(email);
        return ResponseEntity.status(response.getCode()).body(response);
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<Response<String>> register(@RequestBody @Valid UserRegisterDTO userRegisterDTO) {
        Response<String> response = userAuthService.register(
                userRegisterDTO.getEmail(),
                userRegisterDTO.getCode(),
                userRegisterDTO.getPassword()
        );
        return ResponseEntity.status(response.getCode()).body(response);
    }



    /**
     * 获取登录验证码
     */
    @GetMapping("/login/code")
    public void getLoginCode(HttpServletResponse response) {
        userAuthService.generateLoginCode(response);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Response<Map<String, Object>>> login(@RequestBody @Valid UserLoginDTO userLoginDTO) {
        Response<Map<String, Object>> response = userAuthService.login(
                userLoginDTO.getEmail(),
                userLoginDTO.getPassword(),
                userLoginDTO.getCode()
        );
        return ResponseEntity.status(response.getCode()).body(response);
    }
}
